import $http from 'servers/http';
import {
  AbilityItem,
  ApiTokenItem,
  BillingStatisticsItem,
  CallSignatureItem,
  CasResult,
  IndustrySmsStatisticsItem,
  IntelligentCallStatisticsItem,
  MessagesItem,
  OperationLogItem,
  RocketApiResult,
  SensitiveWordItem,
  SignatureItem,
  TemplateItem,
} from 'admin/schema/Cas';
import { OrganizationItem, RoleItem, PermissionItem, ListPage, UserItem } from 'admin/schema/Cas';

export const uploadUrl = `${process.env.REACT_APP_API_URL || ''}/cas/api/resources/files/upload`;
/**
 * 通过cas登录
 */
export const casLogin = (data: {
  username: string;
  password: string;
  verificationCode: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: `/cas/passport/login`,
    data,
  });
};

/**
 * 通过cas手机登录
 */
export const casLoginWithPhone = (data: {
  phone: string;
  verificationCode: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: `/cas/passport/loginWithPhone`,
    data,
  });
};

/**
 * 获取图形验证码
 */
export const getCodeImg = (): Promise<any> => {
  return $http.get(
    {
      url: '/cas/passport/captcha',
    },
    {
      responseType: 'blob',
    }
  );
};

export const sendSmsValidateCode = (data: { type: number; phone: string }): Promise<any> => {
  return $http.post({
    url: '/cas/passport/sendSmsValidateCode',
    data,
  });
};

export const casRetrievePassword = (data: {
  confirmPassword: string;
  password: string;
  phone: string;
  validateCode: string;
}): Promise<any> => {
  return $http.post({
    url: '/cas/passport/retrievePassword',
    data,
  });
};

/**
 * 退出登录
 */
export const casLogout = (): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/passport/logout',
  });
};

/**
 * 获取用户信息
 */
export const getCasUserInfo = (data: { username: string }): Promise<CasResult<any>> => {
  return $http.get({
    url: '/cas/passport/session',
    data,
  });
};

/**
 * 修改密码
 */
export const modifyCasUserPwd = (data: {
  id: string;
  username: string;
  oldPassword: string;
  password: string;
  confirmPassword: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/user/changePassword',
    data,
  });
};

/**
 * 获取单位列表
 */
export const getCasOrganizations = (pid?: string): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/org/list',
    data: {
      pid,
    },
  });
};

/**
 * 获取单位列表-可见列表
 */
export const getCasOrganizationsShow = (): Promise<
  CasResult<Omit<OrganizationItem, 'children' | 'description'>[]>
> => {
  return $http.get({
    url: '/cas/org/list/show',
  });
};

/**
 * 获取单位树
 */
export const getCasOrganizationsTree = (): Promise<CasResult<OrganizationItem[]>> => {
  return $http.get({
    url: '/cas/org/tree',
  });
};
/**
 * 新增单位
 */
export const addCasOrganization = (data: {
  description: string;
  pid: string;
  name: string;
  display: number;
  status: number;
  emergency?: number;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/org/add',
    data,
  });
};

/**
 * 删除单位
 */
export const deleteCasOrganization = (data: { id: string }): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/org/delete',
    data,
  });
};

/**
 * 修改单位
 */
export const updateCasOrganization = (data: {
  description?: string;
  id: string;
  name: string;
  code: string;
  pid: string;
  display: number;
  status: number;
  emergency?: number;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/org/update',
    data,
  });
};

/**
 * 获取角色列表
 */
export const getCasRoles = (): Promise<CasResult<RoleItem[]>> => {
  return $http.post({
    url: '/cas/role/list',
  });
};

/**
 * 新增角色
 */
export const addCasRole = (data: {
  name: string;
  description: string;
  permissions: string[];
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/role/add',
    data,
  });
};

/**
 * 修改角色
 */
export const updateCasRole = (data: {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/role/update',
    data,
  });
};

/**
 * 删除角色
 */
export const deleteCasRole = (data: { id: string }): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/role/delete',
    data,
  });
};

/**
 * 查询角色权限
 */
export const getCasRolePermissions = (roleId: string): Promise<CasResult<PermissionItem[]>> => {
  return $http.get({
    url: '/cas/role/queryPermissions',
    data: {
      roleId,
    },
  });
};

/**
 * 权限_功能树
 */
export const getCasPermissionTree = (): Promise<CasResult<PermissionItem[]>> => {
  return $http.get({
    url: '/cas/permission/tree',
  });
};

/**
 * 获取用户列表
 */
export const getCasUsers = (
  page = 0,
  size = 10,
  data: {
    orgId: string;
    username?: string;
    phone?: string;
    status?: number;
  }
): Promise<CasResult<ListPage<UserItem>>> => {
  return $http.post({
    url: `/cas/user/list?page=${page}&size=${size}`,
    data,
  });
};

/**
 * 新增用户
 */
export const addCasUser = (data: {
  username: string;
  password: string;
  orgId: string;
  status: number;
  roleIds: string;
  nickname?: string;
  phone?: string;
  email?: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/user/add',
    data,
  });
};

/**
 * 修改用户
 */
export const updateCasUser = (data: {
  id: string;
  username: string;
  orgId: string;
  status: number;
  roleIds: string;
  nickname?: string;
  phone?: string;
  email?: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/user/update',
    data,
  });
};

/**
 * 更新角色
 */
export const updateCasUserRole = (data: {
  id: string;
  roleIds: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/user/updateRole',
    data,
  });
};

export const deleteCasUser = (id: string): Promise<CasResult<any>> => {
  return $http.post({
    url: `/cas/user/delete`,
    data: {
      id,
    },
  });
};

/**
 * 重置密码
 */
export const resetCasUserPassword = (data: {
  id: string;
  password: string;
  confirmPassword: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/user/resetPassword',
    data,
  });
};

/**
 * 新增敏感词
 */
export const addSensitiveWord = (data: { word: string }): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/sensitive-word/add',
    data,
  });
};

/**
 * 删除敏感词
 */
export const deleteSensitiveWord = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/sensitive-word/delete/${id}`,
  });
};

/**
 * 获取敏感词列表
 */
export const getSensitiveWords = (
  page = 0,
  size = 10,
  data: {
    word: string;
  }
): Promise<CasResult<ListPage<SensitiveWordItem>>> => {
  return $http.post({
    url: `/cas/sensitive-word/list?page=${page}&size=${size}`,
    data,
  });
};

/**
 * 更新敏感词
 */
export const updateSensitiveWord = (data: {
  id: string;
  word: string;
}): Promise<CasResult<any>> => {
  return $http.put({
    url: '/cas/sensitive-word/update',
    data,
  });
};

/**
 * 敏感词检查
 */
export const checkSensitiveWord = (data: {
  content: string;
}): Promise<CasResult<{ result: boolean; invalidWords: string[] }>> => {
  return $http.post({
    url: '/cas/sensitive-word/check',
    data,
  });
};

/**
 * 获取签名列表
 */
export const getSignatures = (data: {
  pageNo: number;
  pageSize: number;
  type?: string;
  name?: string;
  status?: string;
}): Promise<CasResult<ListPage<SignatureItem>>> => {
  return $http.get({
    url: '/cas/signatures',
    data,
  });
};

/**
 * 获取创建模版的签名列表
 */
export const getCasSignatureList = (data: {
  pageNo: number;
  pageSize: number;
  type?: string;
  name?: string;
  status?: string;
}): Promise<CasResult<ListPage<SignatureItem>>> => {
  return $http.get({
    url: '/cas/signatures/list',
    data,
  });
};

/**
 * 获取签名详情
 */
export const getSignature = (id: string): Promise<CasResult<SignatureItem>> => {
  return $http.get({
    url: `/cas/signatures/${id}`,
  });
};

/**
 * 新增签名
 */
export const addSignature = (data: {
  certificatePath: string;
  description: string;
  idCardBackImagePath: string;
  idCardFrontImagePath: string;
  name: string;
  organizationId: string;
  phone: string;
  powerOfAttorney: string;
  type: string[];
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/signatures',
    data,
  });
};

/**
 * 删除签名
 */
export const deleteSignature = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/signatures/${id}`,
  });
};

/**
 * 更新签名
 */
export const updateSignature = (
  id: string,
  data: {
    certificatePath: string;
    description: string;
    idCardBackImagePath: string;
    idCardFrontImagePath: string;
    name: string;
    organizationId: string;
    phone: string;
    powerOfAttorney: string;
    type: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/signatures/${id}`,
    data,
  });
};

/**
 * 审核签名
 */
export const auditSignature = (
  id: string,
  data: {
    auditBy: string;
    auditStatus: string;
    remark: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/signatures/${id}/audit`,
    data,
  });
};

/**
 * 获取签名审核日志
 */
export const getSignatureAuditLogs = (id: string): Promise<CasResult<any>> => {
  return $http.get({
    url: `/cas/signatures/${id}/logs`,
  });
};

/**
 * 获取模版列表
 */
export const getTemplates = (data: {
  pageNo: number;
  pageSize: number;
  type?: string;
  name?: string;
  status?: string;
}): Promise<CasResult<ListPage<TemplateItem>>> => {
  return $http.get({
    url: '/cas/templates',
    data,
  });
};

/**
 * 新增模版
 */
export const addTemplate = (data: {
  content: string;
  materials: string;
  name: string;
  organizationId: string;
  signatureId: string;
  type: string[];
  ctFileUrl?: string;
  cuFileUrl?: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/templates',
    data,
  });
};

/**
 * 删除模版
 */
export const deleteTemplate = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/templates/${id}`,
  });
};

/**
 * 删除审核成功的模版
 */
export const deleteApprovedTemplate = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/templates/del/${id}`,
  });
};

/**
 * 更新模版
 */
export const updateTemplate = (
  id: string,
  data: {
    content: string;
    materials: string;
    name: string;
    organizationId: string;
    signatureId: string;
    type: string;
    cuFileUrl?: string;
    ctFileUrl?: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/templates/${id}`,
    data,
  });
};

/**
 * 审核模版
 */
export const auditTemplate = (
  id: string,
  data: {
    auditBy: string;
    auditStatus: string;
    remark: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/templates/${id}/audit`,
    data,
  });
};

/**
 * 获取模版详情
 */
export const getTemplate = (id: string): Promise<CasResult<TemplateItem>> => {
  return $http.get({
    url: `/cas/templates/${id}`,
  });
};

/**
 * 获取模版审核日志
 */
export const getTemplateAuditLogs = (id: string): Promise<CasResult<any>> => {
  return $http.get({
    url: `/cas/templates/${id}/logs`,
  });
};

/**
 * 导入模版
 */
export const importTemplate = (data: {
  file: File;
  orgId: string;
  materials: string;
  signatureId: string;
  type: string;
  cuFileUrl?: string;
  ctFileUrl?: string;
}): Promise<CasResult<any>> => {
  const formData = new FormData();
  formData.append('file', data.file);
  formData.append('orgId', data.orgId);
  formData.append('materials', data.materials);
  formData.append('signatureId', data.signatureId);
  formData.append('type', data.type);
  formData.append('cuFileUrl', data.cuFileUrl || '');
  formData.append('ctFileUrl', data.ctFileUrl || '');
  formData.append('cmccFileUrl', '');
  return $http.post({
    url: '/cas/templates/import',
    data: formData,
  });
};

/**
 * 获取能力列表
 */
export const getAbilities = (data: {
  pageNo: number;
  pageSize: number;
  type?: string;
  status?: string;
  year?: string;
}): Promise<CasResult<ListPage<AbilityItem>>> => {
  return $http.get({
    url: '/cas/ability-applications',
    data,
  });
};

/**
 * 新增能力
 */
export const addAbility = (data: {
  org: string;
  quantity: number;
  threshold: number;
  type: string;
  unit: string;
  year: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/ability-applications',
    data,
  });
};

/**
 * 审核能力
 */
export const auditAbility = (
  id: string,
  data: {
    auditBy: string;
    auditStatus: string;
    remark: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/ability-applications/${id}/audit`,
    data,
  });
};

/**
 * 获取能力审核日志
 */
export const getAbilityAuditLogs = (
  id: string
): Promise<
  CasResult<
    {
      id: string;
      operationAt: number;
      operator: string;
      status: string;
      remark: string;
      abilityApplicationId: string;
      createdAt: number;
      taskName: string;
      userInfo: {
        id: string;
        username: string;
        nickname: string;
        phone: string;
        email: string;
        status: number;
        face: string;
        createdTime: number;
      };
    }[]
  >
> => {
  return $http.get({
    url: `/cas/ability-applications/${id}/logs`,
  });
};

/**
 * 获取呼叫签名列表
 */
export const getCallSignatures = (
  pageNo: number,
  pageSize: number,
  data: {
    name?: string;
    status?: string;
  }
): Promise<CasResult<ListPage<CallSignatureItem>>> => {
  return $http.get({
    url: `/cas/api/call-signatures`,
    data: {
      pageNo,
      pageSize,
      ...data,
    },
  });
};

/**
 * 获取呼叫签名详情
 */
export const getCallSignature = (id: string): Promise<CasResult<CallSignatureItem>> => {
  return $http.get({
    url: `/cas/api/call-signatures/${id}`,
  });
};
/**
 * 新增呼叫签名
 */
export const addCallSignature = (data: {
  concurrency: number;
  name: string;
  organization: string;
  scriptScenario: string;
  securityCommitment: string;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/api/call-signatures',
    data,
  });
};

/**
 * 删除呼叫签名
 */
export const deleteCallSignature = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/api/call-signatures/${id}`,
  });
};

/**
 * 更新呼叫签名
 */
export const updateCallSignature = (
  id: string,
  data: {
    concurrency: number;
    name: string;
    organization: string;
    scriptScenario: string;
    securityCommitment: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/api/call-signatures/${id}`,
    data,
  });
};

/**
 * 审核呼叫签名
 */
export const auditCallSignature = (
  id: string,
  data: {
    auditBy: string;
    auditStatus: string;
    remark: string;
  }
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/api/call-signatures/${id}/audit`,
    data,
  });
};

/**
 * 获取API Token列表
 */
export const getApiTokens = (
  pageNo: number,
  pageSize: number
): Promise<CasResult<ListPage<ApiTokenItem>>> => {
  return $http.get({
    url: `/cas/api/token/list?pageNo=${pageNo}&pageSize=${pageSize}`,
  });
};

/**
 * 获取API Token详情
 */
export const getApiToken = (id: string): Promise<CasResult<ApiTokenItem>> => {
  return $http.get({
    url: `/cas/api/token/get/${id}`,
  });
};

/**
 * 新增API Token
 */
export const addApiToken = (data: {
  name: string;
  org: string;
  description: string;
  userId: string;
  expireTime?: string;
  enabled: boolean;
}): Promise<CasResult<any>> => {
  return $http.post({
    url: '/cas/api/token/add',
    data,
  });
};

/**
 * 删除API Token
 */
export const deleteApiToken = (id: string): Promise<CasResult<any>> => {
  return $http.delete({
    url: `/cas/api/token/delete/${id}`,
  });
};

/**
 * 更新API令牌有效期限
 */
export const updateApiTokenExpirationTime = (
  expireTime: string,
  id: string
): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/api/token/updateExpirationTime`,
    data: {
      expireTime,
      id,
    },
  });
};

/**
 * 更新API令牌状态
 */
export const updateApiTokenStatus = (enable: boolean, id: string): Promise<CasResult<any>> => {
  return $http.put({
    url: `/cas/api/token/updateStatus`,
    data: {
      enable,
      id,
    },
  });
};

export const getAuditUserByType = (
  type: string,
  templateId?: string
): Promise<
  CasResult<{
    stepAuditUsers: {
      stepName: string;
      auditUserList: {
        userId: string;
        userName: string;
        nickName: string;
      }[];
    }[];
  }>
> => {
  return $http.get({
    url: '/cas/user/getAuditUserByType',
    data: { type, templateId },
  });
};

export const getOperationLogModule = (): Promise<
  RocketApiResult<
    {
      type: string;
    }[]
  >
> => {
  return $http.get({
    url: `/rocket-api/distributedDomain/operationLog/queryOperModule`,
  });
};

export const getOperationLog = (
  pageNo: number,
  pageSize: number,
  ip?: string,
  desc?: string,
  startTime?: string,
  endTime?: string,
  username?: string,
  operModule?: string
): Promise<
  RocketApiResult<{
    totalRecords: number;
    data: OperationLogItem[];
    offset: number;
    pageNo: number;
    totalPages: number;
    pageSize: number;
  }>
> => {
  return $http.get({
    url: `/rocket-api/distributedDomain/operationLog/query`,
    data: {
      pageNo,
      pageSize,
      ip,
      desc,
      startTime,
      endTime,
      username,
      operModule,
    },
  });
};

export const getIndustrySmsStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}): Promise<
  RocketApiResult<{
    overview: IndustrySmsStatisticsItem;
    subtotal: IndustrySmsStatisticsItem;
    dataList: IndustrySmsStatisticsItem[];
  }>
> => {
  return $http.post({
    url: `/rocket-api/distributedDomain/statisticAnalysis/industrySmsDataStatistics`,
    data: {
      orgId,
      startDate,
      endDate,
    },
  });
};

export const exportIndustrySmsStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}) => {
  return $http.post(
    {
      url: `/rocket-api/distributedDomain/statisticAnalysis/industrySmsDataStatistics/export`,
      data: {
        orgId,
        startDate,
        endDate,
      },
    },
    {
      responseType: 'blob',
    }
  );
};

export const getTargetedSmsStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}): Promise<
  RocketApiResult<{
    overview: IndustrySmsStatisticsItem;
    subtotal: IndustrySmsStatisticsItem;
    dataList: IndustrySmsStatisticsItem[];
  }>
> => {
  return $http.post({
    url: `/rocket-api/distributedDomain/statisticAnalysis/targetedSmsDataStatistics`,
    data: {
      orgId,
      startDate,
      endDate,
    },
  });
};

export const exportTargetedSmsStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}) => {
  return $http.post(
    {
      url: `/rocket-api/distributedDomain/statisticAnalysis/targetedSmsDataStatistics/export`,
      data: {
        orgId,
        startDate,
        endDate,
      },
    },
    {
      responseType: 'blob',
    }
  );
};

export const getIntelligentCallStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}): Promise<
  RocketApiResult<{
    overview: IntelligentCallStatisticsItem;
    subtotal: IntelligentCallStatisticsItem;
    dataList: IntelligentCallStatisticsItem[];
  }>
> => {
  return $http.post({
    url: `/rocket-api/distributedDomain/statisticAnalysis/intelligentCallDataStatistics`,
    data: {
      orgId,
      startDate,
      endDate,
    },
  });
};

export const exportIntelligentCallStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}) => {
  return $http.post(
    {
      url: `/rocket-api/distributedDomain/statisticAnalysis/intelligentCallDataStatistics/export`,
      data: {
        orgId,
        startDate,
        endDate,
      },
    },
    {
      responseType: 'blob',
    }
  );
};

export const getBillingStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}): Promise<
  RocketApiResult<{
    overview: BillingStatisticsItem;
    subtotal: BillingStatisticsItem;
    dataList: BillingStatisticsItem[];
  }>
> => {
  return $http.post({
    url: `/rocket-api/distributedDomain/statisticAnalysis/billingDataStatistics`,
    data: {
      orgId,
      startDate,
      endDate,
    },
  });
};

export const exportBillingStatistics = ({
  orgId,
  startDate,
  endDate,
}: {
  orgId: string[];
  startDate: string;
  endDate: string;
}) => {
  return $http.post(
    {
      url: `/rocket-api/distributedDomain/statisticAnalysis/billingDataStatistics/export`,
      data: {
        orgId,
        startDate,
        endDate,
      },
    },
    {
      responseType: 'blob',
    }
  );
};

export const getAbilityApplication = (): Promise<RocketApiResult<string[]>> => {
  return $http.get({
    url: `/rocket-api/distributedDomain/common/abilityApplication`,
  });
};

export const getCasMessages = ({
  pageNo,
  pageSize,
  unreadOnly,
}: {
  pageNo: number;
  pageSize: number;
  unreadOnly?: boolean;
}): Promise<CasResult<ListPage<MessagesItem>>> => {
  return $http.get({
    url: `/cas/api/messages`,
    data: {
      pageNo,
      pageSize,
      unreadOnly,
    },
  });
};

export const readCasMessages = (id: string): Promise<CasResult<null>> => {
  return $http.put({
    url: `/cas/api/messages/${id}/read`,
  });
};

export const getCasMessagesPoll = (): Promise<
  CasResult<null | {
    hasNew: boolean;
    newCount: number;
  }>
> => {
  return $http.get({
    url: `/cas/api/messages/poll`,
  });
};
